#include <dblib.h>
#include <stdafx.h>
#include <jaro.h>
#include <constants.h>
#include <params.h>
#include <stdexcept>

#ifdef __cplusplus
extern "C" {
#endif

RETCODE __declspec(dllexport) xp_dist_jaro(SRV_PROC *srvproc);

#ifdef __cplusplus
}
#endif

RETCODE __declspec(dllexport) xp_dist_jaro(SRV_PROC *srvproc)
{

	RETCODE rc = XP_NOERROR;
	params *p1 = new params();
	params *p2 = new params();
	params *p3 = new params();
	params *p4 = new params();
	double dist = 0.0;
	INT distl = 0;
	int c[2] = {0, 1};
	int numparams = params::getparamcount(srvproc);
	try 
	{
		if (numparams != 4) {
			Dblib::printerror(srvproc, USAGE_JARO);
			rc = XP_ERROR;
		}
		if (rc == XP_NOERROR) {
			params::getparam(srvproc, 1, p1);
			params::getparam(srvproc, 2, p2);
			params::getparam(srvproc, 3, p3);
			params::getparam(srvproc, 4, p4);
			if (p1->isoutput || p2->isoutput || !p3->isoutput || p4->isoutput) {
				Dblib::printerror(srvproc, USAGE_JARO);
				rc = XP_ERROR;
			}
		}
		if (rc == XP_NOERROR) {
			std::string options = strupr((char *)p4->cdata);
			int w = (int)options.find("I+");
			int caseinsensitive = 1;
			if (w > -1) {
				caseinsensitive = 0;
			}
			int transerrors = 1;
			w = (int)options.find("T+");
			if (w > -1) {
				transerrors = 0;
			}
			dist = strcmp95((char *)p1->cdata, (char *)p2->cdata, p1->length, p2->length, transerrors, caseinsensitive);
			distl = (ULONG)(dist * 10000.0);
		}
	} catch (std::exception ex) {
		Dblib::printerror(srvproc, ERR_JARO_EXCEPTION);
		rc = XP_ERROR;
	}
	if (rc == XP_NOERROR)
		srv_paramsetoutput(srvproc, 3, (BYTE *)&distl, 4, FALSE);
	else
		srv_paramsetoutput(srvproc, 3, (BYTE *)&distl, 4, TRUE);
	if (p1 != NULL)
		delete p1;
	p1 = NULL;
	if (p2 != NULL)
		delete p2;
	p2 = NULL;
	if (p3 != NULL)
		delete p3;
	p3 = NULL;
	if (p4 != NULL)
		delete p4;
	p4 = NULL;
	srv_senddone(srvproc, SRV_DONE_MORE | SRV_DONE_COUNT, (DBUSMALLINT)0, (DBINT)0);
	return rc;
}

